#! user/bin/python
# -*- coding: utf-8 -*-

"""
Created on 2021/8/24 14:35

@File: 可复用的表单布局类_form.py
@Author: LT
@Description: Use of this module
"""
from tkinter import *

entrysize = 40


class Form:
    def __init__(self, labels, parent=None):                            # parent应该也可以为Tk()
        labelsize = max(len(x) for x in labels) + 2                     # 标签名长度可相对灵活变动
        box = Frame(parent)
        box.pack(expand=YES, fill=X)
        rows = Frame(box, bd=2, relief=GROOVE)                          # 框架里头搭框架，是所有单个行框架依赖的总框架
        rows.pack(side=TOP, expand=YES, fill=X)
        self.content = {}                                               # content存放着标签名:entry值
        for label in labels:
            row = Frame(rows)                                           # 以来行总框架的单个行框架
            row.pack(fill=X)                                            # side不指定默认为TOP
            Label(row, text=label, width=labelsize).pack(side=LEFT)     # 在单行框架的左侧放置标签名
            entry = Entry(row, width=entrysize)
            entry.pack(side=RIGHT, expand=YES, fill=X)                  # 在单行框架的右侧放置输入栏
            self.content[label] = entry                                 # 保留对其引用

        Button(parent, text="Exit", command=self.onExit, width=6).pack(side=RIGHT)
        Button(parent, text="Submit", command=self.onSubmit).pack(side=RIGHT)
        box.bind("<Return>", lambda event: self.onSubmit)

    def onExit(self):
        Tk().quit()                                                     # 做个总退出

    def onSubmit(self):
        for key in self.content:
            print(key, "\t=>\t", self.content[key].get())               # 对entry对象使用get方法获取输入的内容


class DynamicForm(Form):
    def __init__(self, labels=None):
        labels = input("Enter left field names: ").split()
        Form.__init__(self, labels)

    def onSubmit(self):
        print("Fields values...")
        Form.onSubmit(self)
        self.onExit()


if __name__ == '__main__':
    import sys
    if len(sys.argv) == 1:
        Form(["Name", "Age", "Job"])
    else:
        DynamicForm()
    mainloop()
